package com.donghua.controller;

import com.donghua.entity.LoginTicket;
import com.donghua.entity.User;
import com.donghua.service.FollowService;
import com.donghua.service.UserService;
import com.donghua.util.*;
import com.donghua.vo.UserDetailInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.donghua.enums.StatusCodeEnum.SUCCESS;

@Controller
public class FollowController implements CommunityConstant {

    @Autowired
    private FollowService followService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping(path = "/follow", method = RequestMethod.POST)
    @ResponseBody
    public Result<?> follow(int entityType, int entityId) {
        User user = hostHolder.getUser();

        followService.follow(user.getId(), entityType, entityId);

        return Result.ok(SUCCESS.getCode(), SUCCESS.getMsg());
    }

    @RequestMapping(path = "/unfollow", method = RequestMethod.POST)
    @ResponseBody
    public Result<?> unfollow(int entityType, int entityId) {
        User user = hostHolder.getUser();

        followService.unfollow(user.getId(), entityType, entityId);

        return Result.ok(SUCCESS.getCode(), SUCCESS.getMsg());
    }

    // 关注列表
    @RequestMapping(path = "/followees/{userId}", method = RequestMethod.GET)
    @ResponseBody
    public Result<?> getFollowees(@PathVariable("userId") int userId, int offset, int limit, HttpServletRequest request) {
        User user = userService.findUserById(userId);
        if (user == null) {
            throw new RuntimeException("该用户不存在!");
        }
        //用户信息
        Map<String, Object> data = new HashMap<>();
        UserDetailInfo userDetailInfo = new UserDetailInfo();
        userDetailInfo.setId(user.getId());
        userDetailInfo.setUsername(user.getUsername());
        userDetailInfo.setNickName(user.getNickName());
        userDetailInfo.setDescription(user.getDescription());
        userDetailInfo.setHeaderUrl(user.getHeaderUrl());
        userDetailInfo.setCreateTime(user.getCreateTime());
        userDetailInfo.setStatus(user.getStatus());
        userDetailInfo.setType(user.getType());
        userDetailInfo.setBackgroundUrl(user.getBackgroundUrl());
        data.put("user", userDetailInfo);
        // 从cookie中获取凭证
        String ticket = CookieUtil.getValue(request, "ticket");
        boolean flag = false;
        if (ticket != null) {
            // 查询凭证
            String redisKey = RedisKeyUtil.getTicketKey(ticket);
            LoginTicket loginTicket = (LoginTicket) redisTemplate.opsForValue().get(redisKey);
            // 检查凭证是否有效
            if (loginTicket != null && loginTicket.getStatus() == 0 && loginTicket.getExpired().after(new Date())) {
                // 根据凭证查询用户
                User user1 = userService.findUserById(loginTicket.getUserId());
                hostHolder.setUser(user1);
                flag = true;
            }
        }
        List<Map<String, Object>> userList = followService.findFollowees(userId, offset, limit);
        if (userList != null) {
            for (Map<String, Object> map : userList) {
                UserDetailInfo u = (UserDetailInfo) map.get("user");
                if(!flag) {
                    map.put("hasFollowed", false);
                } else {
                    map.put("hasFollowed", hasFollowed(u.getId()));
                }
            }
        }
        data.put("users", userList);
        return Result.ok(SUCCESS.getCode(), SUCCESS.getMsg(), data);
    }

    // 粉丝列表
    @RequestMapping(path = "/followers/{userId}", method = RequestMethod.GET)
    @ResponseBody
    public Result<?> getFollowers(@PathVariable("userId") int userId, int offset, int limit, HttpServletRequest request) {
        User user = userService.findUserById(userId);
        if (user == null) {
            throw new RuntimeException("该用户不存在!");
        }
        //用户信息
        Map<String, Object> data = new HashMap<>();
        UserDetailInfo userDetailInfo = new UserDetailInfo();
        userDetailInfo.setId(user.getId());
        userDetailInfo.setUsername(user.getUsername());
        userDetailInfo.setNickName(user.getNickName());
        userDetailInfo.setDescription(user.getDescription());
        userDetailInfo.setHeaderUrl(user.getHeaderUrl());
        userDetailInfo.setCreateTime(user.getCreateTime());
        userDetailInfo.setStatus(user.getStatus());
        userDetailInfo.setType(user.getType());
        userDetailInfo.setBackgroundUrl(user.getBackgroundUrl());
        data.put("user", userDetailInfo);
        // 从cookie中获取凭证
        String ticket = CookieUtil.getValue(request, "ticket");
        boolean flag = false;
        if (ticket != null) {
            // 查询凭证
            String redisKey = RedisKeyUtil.getTicketKey(ticket);
            LoginTicket loginTicket = (LoginTicket) redisTemplate.opsForValue().get(redisKey);
            // 检查凭证是否有效
            if (loginTicket != null && loginTicket.getStatus() == 0 && loginTicket.getExpired().after(new Date())) {
                // 根据凭证查询用户
                User user1 = userService.findUserById(loginTicket.getUserId());
                hostHolder.setUser(user1);
                flag = true;
            }
        }
        List<Map<String, Object>> userList = followService.findFollowers(userId, offset, limit);
        if (userList != null) {
            for (Map<String, Object> map : userList) {
                UserDetailInfo u = (UserDetailInfo) map.get("user");
                if(!flag) {
                    map.put("hasFollowed", false);
                } else {
                    map.put("hasFollowed", hasFollowed(u.getId()));
                }
            }
        }

        data.put("users", userList);

        return Result.ok(SUCCESS.getCode(), SUCCESS.getMsg(), data);
    }

    private boolean hasFollowed(int userId) {
        if (hostHolder.getUser() == null) {
            return false;
        }
        return followService.hasFollowed(hostHolder.getUser().getId(), ENTITY_TYPE_USER, userId);
    }

}
